import { Login } from '@/apis/user'
import * as CookiesSave from '@/utils/auth'
import { changeDetSelect, dealMenu, findMenu } from '@/utils/tools'

// import router, { resetRouter } from '@/router'

const state = {
  token: CookiesSave.getToken(),
  role: CookiesSave.getRole(),
  rolemenu: CookiesSave.getRolemenu(),

  defaluthas: CookiesSave.getDefaluthas(),
  menutags: CookiesSave.getMenutags(),

  hospitalId: CookiesSave.getHospitalId(), // 获取医院ID
  userId: CookiesSave.getUserId(),
  apiToken: CookiesSave.getApiToken(),
  sysRole: CookiesSave.getSysRole(),
  consultationsId: '', // 会诊标识
  dataBus: {}, // 公共数据转存转运变量,赋值前先清空
  // consultationsId: CookiesSave.getConsultationsId(),
  name: CookiesSave.getName(),
  inscode: CookiesSave.getInscode(),

  dept: CookiesSave.getDept(),
  insname: CookiesSave.getInsname(),
  rname: CookiesSave.getRname(),
  pri: CookiesSave.getPri(),
  tel: CookiesSave.getTel(),
  roleName: CookiesSave.getRoleName(),

  routerInfo: '',

  avatar: '',
  introduction: '',
  roles: CookiesSave.getRoles(),
  routerPowers: [],
  homePagePath: ''
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_ROLE: (state, role) => {
    state.role = role
  },
  SET_DEFALUTHAS: (state, defaluthas) => {
    state.defaluthas = defaluthas
  },
  SET_MENUTAGS: (state, menutags) => {
    state.menutags = menutags
  },

  SET_ROLEMENU: (state, rolemenu) => {
    state.rolemenu = rolemenu
  },
  SET_APITOKEN: (state, apitoken) => {
    state.apiToken = apitoken
  },
  SET_HOSPITAL_ID: (state, hospitalId) => {
    state.hospitalId = hospitalId
  },
  SET_USERID: (state, userId) => {
    state.userId = userId
  },
  SET_SYSROLE: (state, role) => {
    state.sysRole = role
  },
  SET_CONSULTATIONSID: (state, consultationsId) => {
    state.consultationsId = consultationsId
  },
  SET_DATABUS: (state, dataBus) => {
    state.dataBus = dataBus
  },

  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_RNAME: (state, rname) => {
    state.rname = rname
  },
  SET_INSCODE: (state, inscode) => {
    state.inscode = inscode
  },
  SET_INSNAME: (state, insname) => {
    state.insname = insname
  },
  SET_DEPT: (state, dept) => {
    state.dept = dept
  },
  SET_PRI: (state, pri) => {
    state.pri = pri
  },
  SET_TEL: (state, tel) => {
    state.tel = tel
  },
  SET_DEPTMENT: (state, deptment) => {
    state.deptment = deptment
  },
  SET_ROLENAME: (state, roleName) => {
    state.roleName = roleName
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_ROUTERPOWERS: (state, routerPowers) => {
    state.routerPowers = routerPowers
  },
  SET_HOMEPATH: (state, homePagePath) => {
    state.homePagePath = homePagePath
  },
  SET_ROUTER_INFO: (state, routerInfo) => {
    state.routerInfo = routerInfo
  }
}
const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, md5Psd } = userInfo
    return new Promise((resolve, reject) => {
      Login({
        // mac: 'FFFFFFFFFFFF',
        uname: username.trim(),
        upwd: md5Psd
      }).then(response => {
        console.log(response, 'response');
        if (response.data.status == 0) {
          if (response.data) {
            const data = response.data
            console.log(data, 'data')
            const roleInfo = data
            let role = data.userinfo ? data.userinfo.role ? data.userinfo.role : '' : ''
            let rolemenu = data.userinfo ? data.userinfo.rolemenu ? data.userinfo.rolemenu : '' : ''
            let rname = data.userinfo ? data.userinfo.rname ? data.userinfo.rname : '' : ''
            // 树结构
            let treeData = [{
              label: '报告列表',
              path: '/reportList',
              name: 'reportList',
              icon: 'Document',
              parentId: '0',
              id: '1',
              childrens: [{
                path: '/reportList/echocardiography',
                name: '/echocardiography',
                label: '颈动脉项目',
                id: '6',
                parentId: '1',
                childrens: [{
                  path: '/reportList/echocardiography/echCardiovascularProgramInside',
                  name: '/echCardiovascularProgramInside',
                  label: '颈动脉心血管项目(内部管理)',
                  id: '17',
                  parentId: '6',
                }, {
                  path: '/reportList/echocardiography/echCardiovascularProgramPoint',
                  name: '/echCardiovascularProgramPoint',
                  label: '颈动脉心血管项目',
                  id: '18',
                  parentId: '6',
                }, {
                  path: '/reportList/echocardiography/echCerebrovascularProjectInside',
                  name: '/echCerebrovascularProjectInside',
                  label: '颈动脉脑卒中项目(内部管理)',
                  id: '19',
                  parentId: '6',
                }, {
                  path: '/reportList/echocardiography/echCerebrovascularProjectPoint',
                  name: '/echCerebrovascularProjectPoint',
                  label: '颈动脉脑卒中项目',
                  id: '20',
                  parentId: '6',
                }]
              }, {
                path: '/reportList/otherProject',
                name: '/otherProject',
                label: '颈动脉非国家项目',
                id: '7',
                parentId: '1',
                childrens: [{
                  path: '/reportList/otherProject/hncyPoint',
                  name: '/hncyPoint',
                  label: '河南村医项目',
                  id: '21',
                  parentId: '7',
                }, {
                  path: '/reportList/otherProject/hyPoint',
                  name: '/hyPoint',
                  label: '慧医项目',
                  id: '22',
                  parentId: '7',
                }, {
                  path: '/reportList/otherProject/gjPoint',
                  name: '/gjPoint',
                  label: '筛查项目',
                  id: '23',
                  parentId: '7',
                },
                {
                  path: '/reportList/otherProject/gyPoint',
                  name: '/gyPoint',
                  label: '国药爱心',
                  id: '24',
                  parentId: '7',
                },
                {
                  path: "/reportList/otherProject/xjbctPoint",
                  name: "/xjbctPoint",
                  label: "新疆百草堂",
                  id: "29",
                  parentId: "7",
                },
                {
                  path: "/reportList/otherProject/xxgyjyPoint",
                  name: "/xxgyjyPoint",
                  label: "心血管研究院",
                  id: "30",
                  parentId: "7",
                }
                ]
              }]
            }, {
              path: '/reportReview',
              name: '/reportReview',
              label: '报告审核',
              icon: 'DocumentCopy',
              parentId: '0',
              id: '2',
              childrens: [{
                path: '/reportReview/carotidArtery',
                name: '/reportReview/carotidArtery',
                label: '超声心动图',
                id: '8',
                parentId: '2',
              }, {
                path: '/reportReview/echocardiography',
                name: '/reportReview/echocardiography',
                label: '颈动脉',
                id: '9',
                parentId: '2',
              }]
            },
            // {
            //   path: '/reportStatistics',
            //   name: 'reportStatistics',
            //   label: '报告统计',
            //   icon: 'DataAnalysis',
            //   parentId: '0',
            //   id: '3',
            //   childrens: [{
            //     path: '/reportStatistics/reportAudit',
            //     name: 'reportAudit',
            //     label: '审核类',
            //     id: '10',
            //     parentId: '3',
            //   }, {
            //     path: '/reportStatistics/reportNonAudit',
            //     name: 'reportNonAudit',
            //     label: '非审核类',
            //     id: '11',
            //     parentId: '3',
            //   }]
            // },
            {
              path: "/statisticalAnalysis",
              name: "statisticalAnalysis",
              label: "统计分析",
              icon: require("@/images/menu3.png"),
              parentId: "0",
              id: "3",
              childrens: [
                {
                  path: "/statisticalAnalysis/screeningSituation",
                  name: "screeningSituation",
                  label: "筛查情况",
                  parentId: "3",
                  id: "31",
                },
                {
                  path: "/statisticalAnalysis/operationSituation",
                  name: "operationSituation",
                  label: "运营情况看板",
                  parentId: "3",
                  id: "32",
                },
                {
                  path: "/statisticalAnalysis/reportStatistics",
                  name: "reportStatistics",
                  label: "报告统计",
                  parentId: "3",
                  id: "33",
                  childrens: [
                    {
                      path: "/statisticalAnalysis/reportStatistics/reportAudit",
                      name: "reportAudit",
                      label: "审核类",
                      id: "10",
                      parentId: "33",
                    },
                    {
                      path: "/statisticalAnalysis/reportStatistics/reportNonAudit",
                      name: "reportNonAudit",
                      label: "非审核类",
                      id: "11",
                      parentId: "33",
                    },
                  ],
                },
              ],
            },
            {
              path: '/sessionInfo',
              name: 'sessionInfo',
              label: '场次信息',
              icon: 'Finished',
              parentId: '0',
              id: '4',
              childrens: [{
                path: '/sessionInfo/huiyiProject',
                name: 'huiyiProject',
                label: '场次-慧医',
                id: '12',
                parentId: '4',
              }]
            }, {
              path: '/systemManagement',
              name: 'systemManagement',
              label: '系统管理',
              icon: 'Setting',
              parentId: '0',
              id: '5',
              childrens: [{
                path: '/systemManagement/equipmentManagement',
                name: 'equipmentManagement',
                label: '设备管理',
                id: '13',
                parentId: '5',
              }, {
                path: '/systemManagement/pactManagement',
                name: 'pactManagement',
                label: '合约管理',
                id: '14',
                parentId: '5',
                childrens: [{
                  path: '/systemManagement/equipmentManagement/pactAudit',
                  name: 'pactAudit',
                  label: '审核类',
                  id: '25',
                  parentId: '14',
                }, {
                  path: '/systemManagement/equipmentManagement/pactNonAudit',
                  name: 'pactNonAudit',
                  label: '非审核类',
                  id: '26',
                  parentId: '14',
                }]
              }, {
                path: '/systemManagement/hospitalManagement',
                name: 'hospitalManagement',
                label: '机构管理',
                id: '15',
                parentId: '5',
                childrens: [{
                  path: '/systemManagement/hospitalManagement/hospitalManagementInside',
                  name: 'hospitalManagementInside',
                  label: '项目点管理',
                  id: '27',
                  parentId: '15',
                }, {
                  path: '/systemManagement/hospitalManagement/auditHospitalManagement',
                  name: 'auditHospitalManagement',
                  label: '审核机构管理',
                  id: '28',
                  parentId: '15',
                }]
              }, {
                path: '/systemManagement/userManagement',
                name: 'userManagement',
                label: '用户管理',
                id: '16',
                parentId: '5',
              }]
            }]
            if (!rolemenu) {
              reject('请配置菜单！')
            } else {
              commit('SET_TOKEN', data.token)
              CookiesSave.setToken(data.token)
              commit('SET_INSCODE', data.inscode)
              CookiesSave.setInscode(data.inscode)
              commit('SET_INSNAME', data.insname)
              CookiesSave.setInsname(data.insname)
              commit('SET_NAME', data.uname)
              CookiesSave.setName(data.uname)
              commit('SET_RNAME', rname)
              CookiesSave.setRname(rname)
              commit('SET_ROLE', role)
              CookiesSave.setRole(role)
              commit('SET_ROLEMENU', rolemenu)
              CookiesSave.setRolemenu(rolemenu)


              let roleMenu = rolemenu ? rolemenu.split(',') : []
              let menuArr = []
              if (roleMenu && roleMenu.length > 0) {
                roleMenu.forEach(el => {
                  menuArr = menuArr.concat(changeDetSelect(el, treeData))
                })
              }
              console.log('=====menuArr====', menuArr);
              let tempMenu = dealMenu([...new Set(menuArr)])
              console.log('=====tempMenu====', tempMenu);
              let loginMenu = findMenu(tempMenu)
              let menuTags = [{
                name: loginMenu[0].path,
                title: loginMenu[0].label
              }]
              commit('SET_DEFALUTHAS', loginMenu[0].path)
              CookiesSave.setDefaluthas(loginMenu[0].path)

              commit('SET_MENUTAGS', JSON.stringify(menuTags))
              CookiesSave.setMenutags(JSON.stringify(menuTags))
            }
            resolve()
          }
        } else {
          reject('用户或密码错误！')
        }
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  //   getInfo({ commit }, info) {
  //     const token = info
  //     return new Promise((resolve, reject) => {
  //       getInfo({token:token}).then(response => {
  //         console.log(response,'response');
  //         if (response.code == 200) {
  //           if (response.data) {
  //             const data = response.data
  //             const roleInfo = data
  //             const butInfo = data.permissions
  //             window.sessionStorage.setItem('getButton',JSON.stringify(butInfo))
  //             commit('SET_HOSPITAL_ID', roleInfo.hospitalId)
  //             CookiesSave.setHospitalId(roleInfo.hospitalId)
  //             commit('SET_USERID', roleInfo.doctorid)
  //             CookiesSave.setUserId(roleInfo.doctorid)
  //             commit('SET_NAME', roleInfo.userLogin.uname)
  //             CookiesSave.setName(roleInfo.userLogin.uname)
  //             commit('SET_INSCODE', roleInfo.userLogin.inscode)
  //             CookiesSave.setInscode(roleInfo.userLogin.inscode)

  //             commit('SET_INSNAME', roleInfo.userLogin.insname)
  //             CookiesSave.setInsname(roleInfo.userLogin.insname)
  //             commit('SET_DEPT', roleInfo.userLogin.dept)
  //             CookiesSave.setDept(roleInfo.userLogin.dept)
  //             commit('SET_RNAME', roleInfo.userLogin.rname)
  //             CookiesSave.setRname(roleInfo.userLogin.rname)

  //             commit('SET_PRI', roleInfo.userLogin.pri)
  //             CookiesSave.setPri(roleInfo.userLogin.pri) 

  //             commit('SET_TEL', roleInfo.userLogin.tel)
  //             CookiesSave.setTel(roleInfo.userLogin.tel)

  //             commit('SET_DEPTMENT', roleInfo.userLogin.dept)
  //             CookiesSave.setDeptment(roleInfo.userLogin.dept)

  //             commit('SET_ROLENAME', roleInfo.hlSysRole.roleName)
  //             CookiesSave.setRoleName(roleInfo.hlSysRole.roleName)
  //             resolve()
  //           }
  //         } else {
  //           reject(response)
  //         }
  //       }).catch(error => {
  //         reject(error)
  //         console.log('错误')
  //       })
  //     })
  //   },

  // get  treeMenu
  //   getRouters({ commit }, info) {
  //     console.log(info,'info');
  //     const token = info
  //     return new Promise((resolve, reject) => {
  //       getRouters({token:token}).then(response => {
  //         console.log(response,'response');
  //         if (response.code == 200) {
  //           if (response.data) {
  //             const data = response.data
  //             const routerInfo = data
  //             commit('SET_ROUTER_INFO', routerInfo) // 存储路由数组
  //             CookiesSave.setRouterInfo(routerInfo)
  //             window.sessionStorage.setItem('getRouters',JSON.stringify(routerInfo))
  //             resolve(response)
  //           }
  //         }else {
  //           reject(response)
  //         }
  //       }).catch(error => {
  //         console.log('error---', error)
  //         reject(error)
  //       })
  //     })
  //   },
  // get user Menu
  //   getMenu({ commit, state }) {
  //     return new Promise((resolve, reject) => {
  //       getMenu(state.userId).then(response => {
  //         if (!response && response.length > 0) {
  //           reject('Verification failed, please Login again.')
  //         }
  //         // 过滤移动端菜单
  //         // const data = response.data[0].menu.filter(item => item.module && item.module.indexOf('4') > -1)
  //         // console.log(99887711, data)
  //         resolve(response.data[0].menu)
  //       }).catch(error => {
  //         console.log('error---', error)
  //         reject(error)
  //       })
  //     })
  //   },

  // user logout
  //   logout({ commit, state, dispatch }) {
  //     return new Promise((resolve, reject) => {
  //       logout(state.token).then(() => {
  //         commit('SET_TOKEN', '')
  //         CookiesSave.removeToken()
  //         commit('SET_ROLES', [])
  //         resetRouter()

  //         commit('SET_APITOKEN', '')
  //         CookiesSave.removeApiToken()
  //         commit('SET_HOSPITAL_ID', '')
  //         CookiesSave.removeHospitalId()
  //         commit('SET_USERID', '')
  //         CookiesSave.removeUserId()
  //         commit('SET_NAME', '')
  //         CookiesSave.removeName()
  //         commit('SET_DEPTMENT', '')
  //         CookiesSave.removeDeptment()
  //         commit('SET_SYSROLE', '')
  //         CookiesSave.removeSysRole()
  //         commit('SET_ROLES', '')
  //         CookiesSave.removeRoles()
  //         commit('SET_CONSULTATIONSID', '')

  //         // CookiesSave.removeConsultationsId()
  //         commit('SET_ROUTERPOWERS', [])
  //         // reset visited views and cached views
  //         // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
  //         dispatch('tagsView/delAllViews', null, {
  //           root: true
  //         })

  //         resolve()
  //       }).catch(error => {
  //         reject(error)
  //       })
  //     })
  //   },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_ROUTERPOWERS', [])
      CookiesSave.removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const token = role + '-token'

      commit('SET_TOKEN', token)
      CookiesSave.setToken(token)

      const {
        roles
      } = await dispatch('getInfo')

      resetRouter()

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', roles, {
        root: true
      })

      // dynamically add accessible routes
      router.addRoutes(accessRoutes)

      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, {
        root: true
      })

      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
